package com.lzq.chatroom_project.controller;

import com.lzq.chatroom_project.common.pojo.Result;
import com.lzq.chatroom_project.common.pojo.ResultCode;
import com.lzq.chatroom_project.common.utils.JacksonUtil;
import com.lzq.chatroom_project.model.*;
import com.lzq.chatroom_project.service.impl.FriendServiceImpl;
import com.lzq.chatroom_project.service.impl.MessageSessionServiceImpl;
import com.lzq.chatroom_project.service.impl.UserServiceImpl;
import com.lzq.chatroom_project.common.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RequestMapping("/messageSession")
@RestController()
public class MessageSessionController {
    @Autowired
    private MessageSessionServiceImpl messageSessionService;

    /**
     * 获取会话列表
     * @param request
     * @return Result(messageSessionList)
     */
    @GetMapping("/getMessageSessionList")
    public Result getMessageSessionList(HttpServletRequest request) {
        log.info("开始执行getMessageSessionList方法");
        String jwt = request.getHeader("user_token");
        Integer userId = (Integer) JwtUtil.getUserIdFromToken(jwt).getData();
        if (userId == null || userId <= 0) {
            log.error("查询到的用户id:{}",userId);
            return Result.failed(ResultCode.FAILED);
        }
        List<MessageSession> messageSessionList = new ArrayList<>();
        //根据userId获取sessionId
        List<Integer> sessionIds = messageSessionService.getSessionIdsByUserId(userId);
        if (sessionIds == null) return Result.success(new ArrayList<>());
        //遍历sessionId,查询到对应session信息,装入messageSession,返回messageSessionList
        for (Integer sessionId : sessionIds) {
            MessageSession messageSession = new MessageSession();
            messageSession.setSessionId(sessionId);
            //获取对应会话的好友列表
            List<Friend> friendList = messageSessionService.getFriendListBySessionId(sessionId,userId);
            messageSession.setFriends(friendList);
            //获取对应好友信息列表及最后一条消息
            messageSession.setLastMessage(messageSessionService.getLastMessageBySessionId(sessionId));
            messageSessionList.add(messageSession);
        }
        System.out.println(messageSessionList);
        return Result.success(messageSessionList);
    }

    /**
     * 增加消息会话
     * @param toUserIdList
     * @param request
     * @return Result(ret)
     */
    @Transactional
    @PostMapping("/addMessageSession")
    public Result addMessageSession(List<Integer> toUserIdList, HttpServletRequest request) {
        log.info("开始执行addMessageSession方法,接收参数:toUserIdList:{}", JacksonUtil.writeValueAsString(toUserIdList));
        if (toUserIdList == null || toUserIdList.size() <= 0) {
            return Result.failed(ResultCode.FAILED);
        }
        String jwt = request.getHeader("user_token");
        Integer fromUserId = (Integer) JwtUtil.getUserIdFromToken(jwt).getData();
        if (fromUserId == null || fromUserId <= 0) {
            log.error("查询到的用户id:{}",fromUserId);
            return Result.failed(ResultCode.FAILED);
        }
        //创建messageSession,添加messageSessionUserItem,记录其sessionId
        Map<String,Integer> ret = new HashMap<>();
        MessageSession messageSession = new MessageSession();
        messageSessionService.addMessageSession(messageSession);
        log.info("创建会话成功,sessionId:{}",messageSession.getSessionId());

        MessageSessionUserItem messageSessionUserItem1 = new MessageSessionUserItem();
        messageSessionUserItem1.setSessionId(messageSession.getSessionId());
        messageSessionUserItem1.setUserId(fromUserId);
        messageSessionService.addMessageSessionUserItem(messageSessionUserItem1);

        for (int i = 0; i<toUserIdList.size(); i++) {
            MessageSessionUserItem messageSessionUserItem2 = new MessageSessionUserItem();
            messageSessionUserItem2.setSessionId(messageSession.getSessionId());
            messageSessionUserItem2.setUserId(toUserIdList.get(i));
            messageSessionService.addMessageSessionUserItem(messageSessionUserItem2);
        }
        ret.put("sessionId", messageSession.getSessionId());
        return Result.success(ret);
    }


}
